from flask import request
from flask_sqlalchemy import SQLAlchemy
from packages.core.auth.login_user_holder import LoginUserHolder
from modules.sys.models.vis_log import VisLog
from packages.tools.base_tool import generate_id, get_client_ip, parse_user_agent
from packages.tools.db_tool import DbTool
from sqlalchemy import desc
from packages.core.db.decorators import Transactional
from packages.common.base import IdForm, IdsForm
from modules.sys.validators.vis_log_validator import VisLogForm, VisLogPageForm


class VisLogService():
    """
    系统访问日志表模块业务处理类
    """
    def __init__(self, db: SQLAlchemy):
        self.model = VisLog
        self.db = db

    @Transactional()
    def save(self, form: VisLogForm):
        """
        添加
        :param form:
        :return:
        """
        model = self.model(**form.data)
        model.id = generate_id()
        model.createUser = LoginUserHolder.get_user_id()
        model.updateUser = LoginUserHolder.get_user_id()

        self.db.session.add(model)

    @Transactional()
    def update(self, form: VisLogForm):
        """
        修改
        :param form:
        :return:
        """
        model = self.model(**form.data)

        model.updateUser = LoginUserHolder.get_user_id()

        self.db.session.query(self.model).filter_by(id=form.id.data).update(
            model.to_dict()
        )

    @Transactional()
    def remove(self, form: IdsForm):
        """
        删除
        :param form:
        :return:
        """
        self.model().remove(self.model, form.ids.data)

    def detail(self, form: IdForm):
        """
        通过id获取信息
        :param form:
        :return:
        """
        model = self.db.session.query(self.model).get(form.id.data)
        return model

    def page(self, form: VisLogPageForm):
        """
        分页查询用户列表
        :param form:
        :return:
        """
        # 可通过form.data获取所有提交参数
        # 可通过form.pageNum.data获取pageNum
        # 可通过form.pageSize.data获取pageSize
        # page=self.db.query(User).filter().paginate(form.pageNum.data, form.pageSize.data,False)
        pageNum = form.data.get("pageNum", 1)
        pageSize = form.data.get("pageSize", 10)
        page = (
            DbTool.filter_by_custom(VisLog)
            .order_by(desc(VisLog.visTime))
            .paginate(page=pageNum, per_page=pageSize, error_out=False)
        )
        return self.model.to_page(page)

    def save_vis_log(self, visType, account, success, message):
        id = generate_id()
        userAgentStr = request.headers.get("User-Agent")
        userAgentDict = parse_user_agent(userAgentStr)
        os = userAgentDict.get("os")
        browser = userAgentDict.get("browser")
        ip = get_client_ip(request)
        self.db.session.add(
            VisLog(
                id=id,
                name=visType.msg,
                visType=visType.code,
                account=account,
                success=success,
                message=message,
                os=os,
                browser=browser,
                ip=ip,
            )
        )
